package com.zhao.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhao.dao.AddressMapper;
import com.zhao.dao.RoleMapper;
import com.zhao.dao.UserMapper;
import com.zhao.po.Address;
import com.zhao.po.User;
import com.zhao.po.vo.UserDetail;
import com.zhao.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private AddressMapper addressMapper;

	/**
	 * 查询所有用户的详细信息(包括角色，地址的详细信息)
	 * 
	 * @return
	 */
	public List<UserDetail> getAll(UserDetail user) {
		// TODO Auto-generated method stub
		return userMapper.getAll(user);
	}

	/**
	 * 添加人员信息
	 * 
	 * @param User
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public void add(UserDetail userDetail)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		// TODO Auto-generated method stub
		// user里面有用户的基本信息，还要存储提供的地址信息
		// 这里需要先存储地址的信息。返回标识id,接着再存储用户的基本信息
		Address address = userDetail.getAddress();
		addressMapper.insertSelective(address);
		User user = new User();
		PropertyUtils.copyProperties(user, userDetail);
		user.setSendaddrid(address.getAddressid());
		userMapper.insertSelective(user);
	}

	/**
	 * 根据传入的对象更新 这里可能要更改用户的基本信息和用户的地址信息
	 * 
	 * @param User
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public void updateUser(UserDetail userDetail) {
		// 这里是否可以不复制属性？
		/*
		 * User user=new User(); PropertyUtils.copyProperties(user, userDetail);
		 */
		userMapper.updateByPrimaryKeySelective(userDetail);
		addressMapper.updateByPrimaryKey(userDetail.getAddress());
	}

	/**
	 * 这里删除用户，并删除与之关联的地址信息
	 */
	public void deleteUser(Integer id) {
		// TODO Auto-generated method stub
		// 先删除与之关联的地址信息,这里需要获取到用户的地址id，就需要先根据id来查询出用户对象
		User user = userMapper.selectByPrimaryKey(id);
		addressMapper.deleteByPrimaryKey(user.getSendaddrid());
		// 删除掉用户
		userMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 根据用户id来查询User
	 */
	@Override
	public User getById(int userId) {
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(userId);
	}

}
